package com.lg.meng.observable.download;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lg.meng.R;
import com.lg.meng.model.NotificationModel;
import com.lg.meng.model.ResponseVersionData;
import com.lg.meng.utils.NotificationHelper;

import java.io.File;


/**
 * Author: xx
 * Date: 2019/5/2
 * Description: 固件下载、升级
 */

public class NewVersionDownloadService extends Service implements DownloadObserver {
    public static final String TAG = NewVersionDownloadService.class.getName();
    private VersionDownloaderManager downloaderManager;
    private long time;

    @Override
    public void onCreate() {
        super.onCreate();
        downloaderManager = VersionDownloaderManager.getInstance();
        downloaderManager.addObserver(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        downloaderManager.deleteObserver(this);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        ResponseVersionData versionData = (ResponseVersionData) intent.getSerializableExtra("versionData");
        downloaderManager.startDownload("app", versionData);
        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * 显示手机app下载的提示
     */
    private void showAppDownloadNotification() {
        Intent intent = new Intent("notification_clicked");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationHelper.getHelper().newNotifier(NotificationHelper.ID_DOWN_APP).
                setmContext(this).
                setBuilder().
                setPendingIntent(pendingIntent).
                setTicker(getString(R.string.app_name) + "APK下载").
                setWhen(System.currentTimeMillis()).setNotifyId(827).
                setDefaults(NotificationModel.DEFAULT_SOUND).setOngoing(true).setPriority(NotificationModel.PRIORITY_HIGH).
                setNotification().
                setNotificationView(R.layout.layout_notify_down).
                setTextViewText(R.id.down_name, AppUtils.getAppName() + "APK下载中").
                setManager().setIcon().showNotification();

    }

    @Override
    public void onDownloadSuccess(String flagType, FileDownloader downloader, File file) {
        NotificationModel notificationModel;
        switch (flagType) {
            case "app":
                AppUtils.installApp(file);
                notificationModel = NotificationHelper.getHelper().getNotifier(NotificationHelper.ID_DOWN_APP);
                if (notificationModel != null) {
                    notificationModel.cancelNotify();
                }
                break;
        }
        Log.e(TAG, "文件下载成功：" + file.getAbsolutePath() + ",耗时：" + (System.currentTimeMillis() - time) / 1000 + "秒");
    }

    @Override
    public void onDownloading(String flagType, FileDownloader downloader, int progress, int total, int precent) {
        Log.e(TAG, "文件downloading：progress>" + precent + "%");
        NotificationModel notificationModel;
        switch (flagType) {
            case "app":
                notificationModel = NotificationHelper.getHelper().getNotifier(NotificationHelper.ID_DOWN_APP);
                if (notificationModel != null) {
                    notificationModel.setProgress(R.id.down_pro, 100, precent, false)
                            .setTextViewText(R.id.down_tv, "已下载" + precent + "%").setDefaults().showNotification();
                }
                break;
        }

    }

    @Override
    public void onDownloadStart(String flagType, FileDownloader downloader, int fileSize) {
        switch (flagType) {
            case "app":
                showAppDownloadNotification();
                break;
        }
        Log.e(TAG, "开始下载文件 文件总大小：" + fileSize);
        time = System.currentTimeMillis();

    }

    @Override
    public void onDownloadFailed(String flagType, FileDownloader downloader, String msg) {
        Log.e(TAG, "文件下载失败：" + msg);
        ToastUtils.showLong(msg);
        NotificationModel notificationModel;
        switch (flagType) {
            case "app":
                notificationModel = NotificationHelper.getHelper().getNotifier(NotificationHelper.ID_DOWN_APP);
                if (notificationModel != null) {
                    notificationModel.cancelNotify();
                }
                break;
        }
    }

    @Override
    public void onDownloadSpeed(String flagType, FileDownloader downloader, float speed, int remainedTime) {
    }

    @Override
    public void onDownloadCancel(String flagType, FileDownloader downloader) {
        NotificationModel notificationModel;
        switch (flagType) {
            case "app":
                notificationModel = NotificationHelper.getHelper().getNotifier(NotificationHelper.ID_DOWN_APP);
                if (notificationModel != null) {
                    notificationModel.setTextViewText(R.id.down_name, AppUtils.getAppName() + "APK下载 已暂停").setDefaults().showNotification();
                }
                break;
        }
    }

}
